package com.thiswhyme.qrcode;

import com.google.zxing.*;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Hashtable;
import java.util.List;

/**
 * @description: 二维码生成器
 * @author: thiswhyme
 * @date: 2020/9/15
 */
public class QrCodeUtil {
    
    private static final String CHARSET = "utf-8";

    /**
     * 生成二维码到目标路径文件
     * @param content 二维码内容
     * @param targetPath 目标文件路径
     * @param qrConfig 二维码配置
     * @throws IOException
     */
    public static void generateToTarget(String content, String targetPath, QrConfig qrConfig) {
        BufferedImage image = QrCodeUtil.generateQrCode(content, qrConfig);
        mkdirs(targetPath);
        try {
            ImageIO.write(image, qrConfig.getFileType(), new File(targetPath));
        } catch (IOException e) {
            throw new QrCodeException("二维码生成失败");
        }
    }

    /**
     * 生成二维码到BufferedImage
     * @param content 二维码内容
     * @param qrConfig 目标文件路径
     * @return
     * @throws IOException
     */
    public static BufferedImage generateToImage(String content, QrConfig qrConfig) {
        return QrCodeUtil.generateQrCode(content, qrConfig);
    }

    /**
     * 生成二维码到OutputStream
     * @param content 二维码内容
     * @param qrConfig 目标文件路径
     * @param output 输出流
     * @throws IOException
     */
    public static void generateToStream(String content, QrConfig qrConfig, OutputStream output) {
        BufferedImage image = QrCodeUtil.generateQrCode(content, qrConfig);
        try {
            ImageIO.write(image, qrConfig.getFileType(), output);
        } catch (IOException e) {
            throw new QrCodeException("二维码生成失败");
        }
    }

    /**
     * 二维码解码
     * @param file
     * @return
     * @throws Exception
     */
    public static String qrCodeToString(File file) throws Exception {
        BufferedImage image;
        image = ImageIO.read(file);
        if (image == null) {
            return null;
        }
        BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Result result;
        Hashtable hints = new Hashtable();
        hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
        result = new MultiFormatReader().decode(bitmap, hints);
        String resultStr = result.getText();
        return resultStr;
    }

    /**
     * 生成二维码
     * @param content
     * @param qrConfig
     * @return
     * @throws Exception
     */
    private static BufferedImage generateQrCode(String content, QrConfig qrConfig) {
        Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.MARGIN, qrConfig.getMargin());
        BitMatrix bitMatrix = null;
        try {
            bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, qrConfig.getWidth(), qrConfig.getHeight(),
                    hints);
        } catch (WriterException e) {
            throw new QrCodeException("二维码生成失败");
        }
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                if(bitMatrix.get(x, y)) {
                    image.setRGB(x, y, qrConfig.getForeColor());
                } else if(null != qrConfig.getBackColor()){
                    image.setRGB(x, y, qrConfig.getBackColor());
                }
            }
        }

        // 插入图片
        if (null != qrConfig.getLogo()) {
            QrCodeUtil.insertImage(image, qrConfig.getLogo(), qrConfig.getWidth(), qrConfig.getHeight());
        }

        // 插入文字
        if (null != qrConfig.getText() || (null != qrConfig.getExtraTexts() && qrConfig.getExtraTexts().size() > 0)) {
            QrCodeUtil.pressText(image, qrConfig.getText(), qrConfig.getWidth(), qrConfig.getHeight(), qrConfig.getExtraTexts());
        }
        return image;
    }

    /**
     * 添加logo
     * @param source
     * @param config
     * @param qrCodeWidth
     * @param qrCodeHeight
     */
    private static void insertImage(BufferedImage source, QrConfig.LogoConfig config, int qrCodeWidth, int qrCodeHeight) {
        InputStream logo = config.getImage();
        if (null == logo) {
            throw new QrCodeException("文件不存在");
        }
        Image src;
        try {
            src = ImageIO.read(logo);
        } catch (IOException e) {
            throw new QrCodeException("文件读取失败");
        }
        int width = src.getWidth(null);
        int height = src.getHeight(null);

        // 压缩LOGO
        if (width > config.getWidth()) {
            width = config.getWidth();
        }
        if (height > config.getHeight()) {
            height = config.getHeight();
        }
        Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
        BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = tag.getGraphics();
        g.drawImage(image, 0, 0, null);
        g.dispose();
        src = image;

        // 插入LOGO
        Graphics2D graph = source.createGraphics();
        int x = (qrCodeWidth - width) / 2;
        int y = (qrCodeHeight - height) / 2;
        graph.drawImage(src, x, y, width, height, null);
        Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
        try {
            logo.close();
        } catch (IOException e) {
            throw new QrCodeException("文件流关闭失败");
        }
    }

    /**
     * 添加文字
     * @param source
     * @param config
     * @param qrCodeWidth
     * @param qrCodeHeight
     * @param extraTexts
     */
    public static void pressText(BufferedImage source, QrConfig.TextConfig config, int qrCodeWidth, int qrCodeHeight,
                                 List<QrConfig.PositionTextConfig> extraTexts) {
        if(null != config) {
            //x开始的位置：（图片宽度-字体大小*字的个数（需要区分汉字和其他字符，汉字的宽度是其他字符的2倍））/2
            String regex = "[\u4e00-\u9fa5]";
            int hanZiAmount = config.getContent().length() - config.getContent().replaceAll(regex, "").length();
            int startX = (qrCodeWidth - (config.getFontSize() * hanZiAmount) - (config.getFontSize() / 2 * (config.getContent().length() - hanZiAmount))) / 2;
            //y开始的位置：图片高度-（图片高度-图片宽度）/2

            int startY = qrCodeHeight - (qrCodeHeight - qrCodeWidth) / 3;
            if (TextPosition.TOP.equals(config.getPosition())) {
                startY = (qrCodeHeight - qrCodeWidth) / 2;
            }

            Graphics2D g = source.createGraphics();
            g.setColor(config.getColor());
            g.setFont(new Font(config.getFont(), config.getFontStyle(), config.getFontSize()));
            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            g.drawString(config.getContent(), startX, startY);
            g.dispose();
        }

        if(null != extraTexts && extraTexts.size() > 0) {
            extraTexts.forEach(extraText -> {
                Graphics2D g = source.createGraphics();
                g.setColor(extraText.getColor());
                g.setFont(new Font(extraText.getFont(), extraText.getFontStyle(), extraText.getFontSize()));
                g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
                g.drawString(extraText.getContent(), extraText.getStartX(), extraText.getStartY());
                g.dispose();
            });
        }
    }

    /**
     * 创建文件夹
     * @param destPath
     */
    private static void mkdirs(String destPath) {
        File file = new File(destPath);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
    }
}
